﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Diagnostics;
using System.Text.RegularExpressions;
using LOGISTCBUS.Entities;

namespace LOGISTCBUS.DAO
{
    public class TripDAO : BaseDAO
    {
        #region public methods
        public Boolean insert(Trip t)
        {
            var db = new Db();
            db.Connect();
            String sql = "insert into trips (code, origin, destination, description, begin_date, end_date) ";
            sql += "values (@code, @origin, @destination, @description, @begin_date, @end_date);";
            var parameters = new Dictionary<String, Object>();
            parameters["@code"] = t.Code;
            parameters["@origin"] = t.Origin;
            parameters["@destination"] = t.Destination;
            parameters["@description"] = t.Description;
            parameters["@begin_date"] = t.BeginDate;
            parameters["@end_date"] = t.EndDate;
            try
            {
                var sucess = db.Execute(sql, parameters);
                t.Id = Convert.ToInt32(db.Select("select max(t.id) from trips t").Rows[0][0]);
                db.Commit();
                db.Disconnect();
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                db.Rollback();
                db.Disconnect();
                return false;
                throw ex;
            }
        }

        public Boolean update(Trip t)
        {
            var db = new Db();
            db.Connect();
            String sql = "update trips set code = @code, origin = @origin, destination = @destination, description = @description, begin_date = @begin_date, end_date = @end_date where id= @id;";
            var parameters = new Dictionary<String, Object>();
            parameters["@code"] = t.Code;
            parameters["@origin"] = t.Origin;
            parameters["@destination"] = t.Destination;
            parameters["@description"] = t.Description;
            parameters["@begin_date"] = t.BeginDate;
            parameters["@end_date"] = t.EndDate;
            parameters["@id"] = t.Id;
            try
            {
                var sucess = db.Execute(sql, parameters);
                db.Commit();
                db.Disconnect();
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                db.Rollback();
                db.Disconnect();
                return false;
                throw ex;
            }
        }

        public Trip selectById(Int32 id)
        {
            var db = new Db();
            db.Connect();
            var dt = db.Select("select * from trips where id = " + id);
            db.Disconnect();
            if (dt == null || dt.Rows.Count <= 0)
                return null;
            DataRow r = dt.Rows[0];
            var obj = new Trip()
            {
                Id = Convert.ToInt32(r["id"]),
                Code = r["code"].ToString(),
                Origin = r["origin"].ToString(),
                Destination = r["destination"].ToString(),
                Description = r["description"].ToString(),
                BeginDate = r["begin_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["begin_date"]),
                EndDate = r["end_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["end_date"]),
                Removed = Convert.ToBoolean(r["removed"])
            };
            return obj;
        }

        public List<Trip> select()
        {
            var db = new Db();
            db.Connect();
            var lst = new List<Trip>();
            var dt = db.Select("select * from trips where removed = 0 order by id");
            db.Disconnect();
            foreach (DataRow r in dt.Rows)
            {
                lst.Add(new Trip()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Code = r["code"].ToString(),
                    Origin = r["origin"].ToString(),
                    Destination = r["destination"].ToString(),
                    Description = r["description"].ToString(),
                    BeginDate = r["begin_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["begin_date"]),
                    EndDate = r["end_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["end_date"]),
                    Removed = Convert.ToBoolean(r["removed"])
                });
            }
            return lst;
        }

        public List<Trip> select(String origin, String destination, Int32 page, Int32 pageSize)
        {
            var db = new Db();
            db.Connect();
            var lst = new List<Trip>();
            var sql = "select * from trips where removed = 0";
            if (!String.IsNullOrEmpty(origin))
                sql += " and origin like '%" + origin + "%'";
            if (!String.IsNullOrEmpty(destination))
                sql += " and destination like '%" + destination + "%'";
            sql += " order by id";
            var dt = db.Select(sql);
            db.Disconnect();
            foreach (DataRow r in dt.Rows)
            {
                lst.Add(new Trip()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Code = r["code"].ToString(),
                    Origin = r["origin"].ToString(),
                    Destination = r["destination"].ToString(),
                    Description = r["description"].ToString(),
                    BeginDate = r["begin_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["begin_date"]),
                    EndDate = r["end_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["end_date"]),
                    Removed = Convert.ToBoolean(r["removed"])
                });
            }
            return lst.Skip((page - 1) * pageSize).Take(pageSize).ToList();
        }

        public Int32 getCount(String origin, String destination)
        {
            var count = 0;
            var db = new Db();
            db.Connect();
            var lst = new List<Trip>();
            var sql = "select count(*) as qtd from trips where removed = 0";
            if (!String.IsNullOrEmpty(origin))
                sql += " and origin like '%" + origin + "%'";
            if (!String.IsNullOrEmpty(destination))
                sql += " and destination like '%" + destination + "%'";
            var dt = db.Select(sql);
            db.Disconnect();
            if (dt != null && dt.Rows.Count > 0)
            {
                var r = dt.Rows[0];
                count = Convert.ToInt32(r["qtd"]);
            }
            return count;
        }

        public List<Trip> select(String filter)
        {
            var db = new Db();
            db.Connect();
            var lst = new List<Trip>();
            var dt = db.Select("select * from trips where removed = 0 and " + getConditions(filter, "origin", "destination") + " order by id");
            db.Disconnect();
            foreach (DataRow r in dt.Rows)
            {
                lst.Add(new Trip()
                {
                    Id = Convert.ToInt32(r["id"]),
                    Code = r["code"].ToString(),
                    Origin = r["origin"].ToString(),
                    Destination = r["destination"].ToString(),
                    Description = r["description"].ToString(),
                    BeginDate = r["begin_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["begin_date"]),
                    EndDate = r["end_date"] is DBNull ? new Nullable<DateTime>() : Convert.ToDateTime(r["end_date"]),
                    Removed = Convert.ToBoolean(r["removed"])
                });
            }
            return lst;
        }

        public Boolean delete(Trip t)
        {
            var db = new Db();
            db.Connect();
            String sql = getSQLDeleteUpdate("trips", "code");
            var parameters = new Dictionary<String, Object>();
            parameters["@id"] = t.Id;
            var sucess = db.Execute(sql, parameters);
            db.Commit();
            db.Disconnect();
            return sucess;
        }

        public Boolean delete(List<Trip> lst)
        {
            var db = new Db();
            db.Connect();
            var sucess = true;
            foreach (var t in lst)
            {
                String sql = getSQLDeleteUpdate("trips", "code");
                var parameters = new Dictionary<String, Object>();
                parameters["@id"] = t.Id;
                sucess = db.Execute(sql, parameters);
            }
            db.Commit();
            db.Disconnect();
            return sucess;
        }

        public String selectNextCode()
        {
            var code = "000000/yyyy";
            var year = DateTime.Today.Year;
            var y1 = DateTime.Today.ToString("yyyy");
            var y2 = DateTime.Today.ToString("yy");
            var lstMatches = Regex.Matches(code, "[0]+");
            var number = 1;
            var db = new Db();
            db.Connect();
            try
            {
                var conds = "";
                foreach (Match m in lstMatches)
                    conds += " and substring(t.code, " + (m.Index + 1) + ", " + m.Length + ") >= '0' and substring(t.code, " + (m.Index + 1) + ", " + m.Length + ") <= '" + m.Value.Replace("0", "9") + "'";
                var sql = "select (cast(coalesce(substring(max(t.code), " + (lstMatches[0].Index + 1) + ", " + lstMatches[0].Length + "), 0) as integer) + 1) as code " +
                    "from trips t where t.removed=0 " + conds + " and t.code like '" + code.Replace("0", "_").Replace("yyyy", y1).Replace("yy", y2) + "'";
                var dt = db.Select(sql);
                number = Convert.ToInt32(dt.Rows[0][0]);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            foreach (Match m in lstMatches)
                code = code.Remove(m.Index, m.Length).Insert(m.Index, String.Format("{0:" + m.Value + "}", number));
            code = code.Replace("yyyy", DateTime.Today.ToString("yyyy")).Replace("yy", DateTime.Today.ToString("yy"));
            db.Disconnect();
            return code;
        }
        #endregion
    }
}
